package com.jci.vsd.activity.Reim;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.bean.download.FileCallBack;
import com.jci.vsd.bean.download.FileSubscriber;
import com.jci.vsd.network.control.DownloadFileControl;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.Utils;
import com.jci.vsd.view.widget.SimpleToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.ResponseBody;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.jci.vsd.constant.AppConstant.fileStoreDir;

/**
 * Created by liqing on 18/7/27.
 * 我的审批－审批详情—审批单的票据原件
 */

public class WaitApprovalPicActivity extends BaseActivity {
    @BindView(R.id.iv_view_big_pic)
    ImageView ivPic;
    private List<String> selectPic;//图片
    Subscription subscription;//订阅
    private String filePath;//文件路径
    private Boolean isBigImage=false; //是否预览大图

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_image);
        selectPic = new ArrayList<>();
        String url = getIntent().getStringExtra("url");

        if (!TextUtils.isEmpty(url)) {
            String path = Utils.searchlastString(url, "/");

            File file = new File(fileStoreDir + "/" + path);
            filePath = file.getPath();
            if (file.exists()) {

                viewBigPic(filePath);
            } else {
                downLoadPic(path, url);
            }
            Glide.with(WaitApprovalPicActivity.this)
                    .load(url)
                    .into(ivPic);

        }


        initViewEvent();

    }

    @Override
    protected void initViewEvent() {
        ivPic.setOnClickListener(this);
//        backBtn.setOnClickListener(this);
//        titleTxt.setText(getResources().getString(R.string.reim_item_pic));
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.iv_view_big_pic) {
            viewBigPic(filePath);
        }
    }


    //获取报销单图片
    public void downLoadPic(final String fileName, String url) {
        //type ="1": 报销单图片； type＝"2"：报销项图片
        final FileCallBack<ResponseBody> callBack = new FileCallBack<ResponseBody>(fileStoreDir, fileName) {

            @Override
            public void onSuccess(final ResponseBody responseBody) {
                String path = fileStoreDir + "/" + fileName;

                viewBigPic(path);

            }

            @Override
            public void progress(long progress, long total) {
                int progressIndex = (int) (progress * 100 / total);
                Loger.i("progress = " + progress + "," + total + "," + Thread.currentThread().getId() + "," + progressIndex);
//                updateProgressBar.setProgress(progressIndex);
            }

            @Override
            public void onStart() {
                showProgress();
            }

            @Override
            public void onCompleted() {
                //updateProgressBar.setVisibility(View.INVISIBLE);
                dimissProgress();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Loger.e("FileCallback--onError" + e.getMessage());
                dimissProgress();
                SimpleToast.toastMessage(e.getMessage(), Toast.LENGTH_SHORT);
//                updateProgressBar.setVisibility(View.INVISIBLE);
//                sureBtn.setEnabled(true);
//                cancelBtn.setEnabled(true);
            }
        };
        // rx.Observable<ResponseBody> obserable = new DownloadFileControl().downloadReimFile(url);
        rx.Observable<ResponseBody> obserable = new DownloadFileControl().downloadReimFileWithToken(url);
        subscription = obserable.subscribeOn(Schedulers.io())//请求网络 在调度者的io线程
                .observeOn(Schedulers.io()) //指定线程保存文件
                .doOnNext(new Action1<ResponseBody>() {
                    @Override
                    public void call(ResponseBody body) {
                        try {
                            callBack.saveFile(body);
                        } catch (Exception e) {
                            e.printStackTrace();
                            callBack.onError(e);
                            Utils.doException(e);
                        }
                    }
                }).observeOn(AndroidSchedulers.mainThread()) //指定线程保存文件
                .doOnError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Utils.doException(throwable);
                    }
                }).observeOn(AndroidSchedulers.mainThread()) //在主线程中更新ui
                .subscribe(new FileSubscriber<ResponseBody>(VsdApplication.getInstance(), callBack));//在主线程中更新ui
        //new DownloadAppControl().downloadApp(getActivity(),url,callBack);
    }

    private void viewBigPic(String picPath) {
        isBigImage = true;
        selectPic.add(picPath);
        PhotoPreview.builder()
                .setPhotos((ArrayList) selectPic)
                .setShowDeleteButton(false)
                .start(WaitApprovalPicActivity.this, PhotoPreview.REQUEST_CODE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isBigImage){
            finish();
        }
        Loger.e("---onResume--");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Loger.e("---back--");
            WaitApprovalPicActivity.this.finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


}
